package by.sjc.giz.web.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import by.sjc.giz.security.CustomUserDetails;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import by.sjc.giz.model.Account;
import by.sjc.giz.model.Book;
import by.sjc.giz.model.Post;
import by.sjc.giz.service.AccountService;
import by.sjc.giz.service.BookService;
import by.sjc.giz.service.CustomerService;

@Controller
@RequestMapping("/book")
public class BookController {

    public static final Logger logger = Logger.getLogger(BookController.class);

	@Autowired
    private BookService bookService;
	@Autowired
	private AccountService accountService;

	@RequestMapping(value = {"/{id}"})
    public ModelAndView bookInfo(
            @PathVariable("id") int bookId) {
		Book book = bookService.getBookById(bookId);
		List<Post> bookPosts = bookService.getBookPosts(bookId);
		List<String> bookAuthors = book.getAuthorList();
		List<String> bookGenres = book.getGenreList();
        ModelAndView mav = new ModelAndView();
        mav.setViewName("book.info");
        mav.addObject("book",book);
        mav.addObject("bookPosts",bookPosts);
        mav.addObject("bookAuthors",bookAuthors);
        mav.addObject("bookGenres",bookGenres);
        return mav;
    }

    @PreAuthorize("isFullyAuthenticated()")
	@RequestMapping(value="/{id}/addPost",method= { RequestMethod.POST })
    @ResponseBody
    public Post addPost(
    		@PathVariable("id") Book book,
            @RequestParam String postText,
            Authentication authentication) {

        Account account = ((CustomUserDetails) authentication.getPrincipal()).getAccount();
        assert null != account;
        Post post = new Post(book, account, postText);
        accountService.addPost(post);
        logger.info("added post="+post);
        return post;
    }
	
    @RequestMapping(value = {"/genre/{genre}"})
    public ModelAndView bookByGenre() {

        ModelAndView mav = new ModelAndView();
        return mav;
    }
}
